package logview.mbeans;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Properties;

import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.ObjectName;

import logview.InitServlet;

public class PropertyLogFile implements PropertyLogFileMBean {
	private static transient final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(PropertyLogFile.class);
	private MBeanServer server = null;
	private File file;
	
	@SuppressWarnings("unchecked")
	public PropertyLogFile() {
		ArrayList srv = MBeanServerFactory.findMBeanServer(InitServlet.agentId);
		if (srv!=null && srv.size()==1) {
			this.server = (MBeanServer) srv.get(0);
		}
	}
	
	public void addAll() {
		final Properties p = new Properties();
		try {
			p.load(new FileInputStream(file));
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		for (Object id : p.keySet()) {
			Object file = p.get(id);
			
			// Create logfile MBean and register it
			LogFile l = new LogFile();
			l.setId((String)id);
			l.setFilename((String)file);
			try {
				ObjectName objectName = l.getObjectName();
				log.debug("Registering "+objectName);
//				ObjectInstance oi = server.createMBean(LogFile.class.getName(), objectName);
//				server.invoke(oi.getObjectName(), "setId", new Object[]{id}, new String[]{String.class.getName()});
				server.registerMBean(l, objectName);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	public void removeAll() {
		// TODO Auto-generated method stub
		
	}

	public void setFilename(String filepath) {
		File f = new File(filepath);
		if (!f.exists()) {
			throw new IllegalArgumentException("file "+filepath+" does not exist");
		}
		if (!f.canRead()) {
			throw new IllegalArgumentException("file "+filepath+" is unreadable");
		}
		this.file = f;
	}
	
	public ObjectName getObjectName() {
		if (this.file==null)
			throw new IllegalStateException("filepath is null");
		try {
			return ObjectName.getInstance(InitServlet.DOMAIN+":filepath="+this.file.getAbsolutePath()+",type="+PropertyLogFile.class.getName());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public void setServer(MBeanServer server) {
		this.server = server;
	}

}
